package com.yihaodian.search;

import java.util.Map;
import java.util.Queue;

import com.yihaodian.index.meta.shard.Shard;
import com.yihaodian.search.fetch.FetchSearchResult;
import com.yihaodian.search.query.QuerySearchResult;

/**
 * A cache that store the Map instance which could be used in every query.
 * @author zhaowei1
 *
 */
public class SearchCache {
    private final Queue<Map<Shard, QuerySearchResult>> cacheQueryResults = ConcurrentCollections.newQueue();
    
    private final Queue<Map<Shard, FetchSearchResult>> cacheFetchResults = ConcurrentCollections.newQueue();

    public Map<Shard, QuerySearchResult> obtainQueryResults() {
        Map<Shard, QuerySearchResult> queryResults;
        while ((queryResults = cacheQueryResults.poll()) == null) {
            cacheQueryResults.offer(ConcurrentCollections.<Shard, QuerySearchResult>newConcurrentMap());
        }
        return queryResults;
    }

    public void releaseQueryResults(Map<Shard, QuerySearchResult> queryResults) {
        queryResults.clear();
        cacheQueryResults.offer(queryResults);
    }
    
    public Map<Shard, FetchSearchResult> obtainFetchResults() {
        Map<Shard, FetchSearchResult> fetchResults;
        while ((fetchResults = cacheFetchResults.poll()) == null) {
            cacheFetchResults.offer(ConcurrentCollections.<Shard, FetchSearchResult>newConcurrentMap());
        }
        return fetchResults;
    }

    public void releaseFetchResults(Map<Shard, FetchSearchResult> fetchResults) {
        fetchResults.clear();
        cacheFetchResults.offer(fetchResults);
    }
}
